package com.opennews.openplatform.dataaggregatorreactiveservice.service

import kotlinx.coroutines.reactor.awaitSingle
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient

@Service
class OrderService(
    private val productService: ProductService,
) {
    private val webClient: WebClient = WebClient.create()

    suspend fun queryList(): List<Map<String, Any>> {
        val orders: List<Map<String, Any>> = webClient.get()
            .uri("lb://order-service/api/orders")
            .retrieve()
            .bodyToMono(List::class.java)
            .awaitSingle() as List<Map<String, Any>>

        // Extract productIds from orders
        val productIds = orders.map { it["productId"] as String }

        // Fetch products based on productIds
        val products: List<Map<String, Any>> = productService.query(productIds)

        // Merge product data into the orders
        return orders.map { order ->
            val product = products.find { it["id"] == order["productId"] }

            product?.let {
                (order as MutableMap)["product"] = mapOf(
                    "id" to it["id"],
                    "title" to it["title"]
                )
            }

            (order as MutableMap).remove("productId")
            order
        }
    }
}